﻿using Fly.Domain.Models;
using Fly.Domain.Services;
using Fly.Domain.Services.Messaging;
using Fly.Web.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Fly.Web.Controllers
{
    public class PostController : BaseController
    {
        //用户中心
        [AllowAnonymous]
        public ActionResult Index(int pageIndex = 1)
        {
            //获取第一页的三十条数据
            var request = new GetPagePostsRequest(pageIndex, PageSize);
            var response = new PostService().GetPagePostsByFilter(request);
            return View(response);
        }
        //未结贴
        [AllowAnonymous]
        public ActionResult Unsolved(int pageIndex = 1)
        {
            var request = new GetPagePostsRequest(pageIndex, PageSize)
            {
                PostStatus = PostStatus.Open
            };
            var response = new PostService().GetPagePostsByFilter(request);
            return View("Index", response);
        }
        //已采纳
        [AllowAnonymous]
        public ActionResult Solved(int pageIndex = 1)
        {
            var request = new GetPagePostsRequest(pageIndex, PageSize)
            {
                PostStatus = PostStatus.Close
            };
            var response = new PostService().GetPagePostsByFilter(request);
            return View("Index", response);
        }
        //精贴
        [AllowAnonymous]
        public ActionResult Wonderful(int pageIndex = 1)
        {
            var request = new GetPagePostsRequest(pageIndex, PageSize)
            {
                IsBoutique = true
            };
            var response = new PostService().GetPagePostsByFilter(request);
            return View("Index", response);
        }
        //详情
        [AllowAnonymous]
        public ActionResult Detail(int postId)
        {
            var service = new PostService();
            var post = service.GetPostById(postId);
            service.HitsPlusOne(post);
            ViewBag.CurrentUserId = CurrentUserId;
            ViewBag.IsAdmin = IsAdmin;

            var comments = new CommentService().GetPageCommentsByPostId(1, 20, postId);
            if (comments.IsSuccess && IsLogin)
            {
                var likeService = new LikeService();
                foreach (var item in comments.Pages.Items)
                {
                    item.IsLike = likeService.ZanIsExists(item.Id, CurrentUserId);
                }
            }
            ViewBag.Comments = comments;

            return View(post);
        }
        //发布帖子
        public ActionResult Add()
        {
            var postCategoryResponse = new PostCategoryService().GetPostCategories();
            ViewBag.PostCategories = postCategoryResponse.Items;

            return View();
        }
        //编辑帖子
        public ActionResult Edit(int postId)
        {
            var service = new PostService();
            if (!service.CheckIsEdit(CurrentUserId, postId))
            {
                return View();
            }
            var post = service.GetPostById(postId);
            ViewBag.PostCategories = new PostCategoryService().GetPostCategories().Items;
            return View(post);
        }
        //我的求解
        public ActionResult MinePost()
        {
            var page = Request["page"];
            var request = new GetPagePostsRequest(Convert.ToInt32(page), 10)
            {
                UserId = CurrentUserId
            };

            var response = new PostService().GetPagePostsByFilter(request);
            if (response.IsSuccess)
            {
                var rows = response.Pages.Items.Select(p =>
                {
                    return new
                    {
                        status = p.IsBoutique ? 1 : 0,
                        accept = p.PostStatus == PostStatus.Close ? 0 : -1,
                        id = p.Id,
                        title = p.Title,
                        time = p.CreateTime.ToString("yyyy-MM-dd HH:ss:mm"),
                        hits = p.Hits,
                        comment = p.CommentCount
                    };
                });


                return JsonResultForFly(0, response.Message, rows);
            }

            return JsonResultForFly(0, "暂无数据", new { });
        }
        //点赞
        [AllowAnonymous]
        public ActionResult JieDaZan(LikeModel model)
        {
            if (!IsLogin)
                return JsonResultForFly(1, "请先登录.");
            var response = new CommentService().AddOrRemoveLike(model.Id, model.Ok, CurrentUserId);
            return JsonResultForFly(response.IsSuccess ? 0 : 1, response.Message);
        }
        //删除帖子
        public ActionResult Delete()
        {
            if (!IsAdmin)
                return JsonResultForFly(1, "非法操作.");
            var id = Request["id"];

            var response = new PostService().DeletePost(Convert.ToInt32(id));

            return JsonResultForFly(response.IsSuccess ? 0 : 1, response.Message);
        }
        //设置
        public ActionResult Set(PostSetModel model)
        {
            if (!IsAdmin || model == null)
                return JsonResultForFly(1, "非法操作.");

            var response = new PostService().PostSet(model.Id, model.Rank, model.Field,CurrentUserId);

            return JsonResultForFly(response.IsSuccess ? 0 : 1, response.Message);
        }
        //帖子采纳
        [HttpPost]
        public ActionResult Accept(int id)
        {
            var response = new CommentService().Accept(CurrentUserId, id);

            return JsonResultForFly(response.IsSuccess ? 0 : 1, response.Message);
        }
        //回帖
        [HttpPost]
        [AllowAnonymous]
        [ValidateInput(false)]
        public ActionResult Reply(ReplyModel model)
        {
            if (!IsLogin)
                return JsonResultForFly(1, "你还没有登录呢，请登录后再来回复吧！");
            if (!EmailConfirmed)
                return JsonResultForFly(1, "请先验证邮箱哦.");
            var names = new List<string>();
            var arrNames = model.Content.Split('@');
            foreach (var item in arrNames)
            {
                var name = item.Length > 0 ? item.Substring(0, item.IndexOf(' ')) : item;
                if (name.Length > 0)
                    names.Add(name);
            }

            var entity = new Comment
            {
                UserId = CurrentUserId,
                PostId = model.Id,
                Like = 0,
                Content = model.Content,
                CreateTime = DateTime.Now,
                Ticks = DateTime.Now.Ticks
            };

            var response = new CommentService().AddComment(entity, CurrentUserId, names);

            return JsonResultForFly(response.IsSuccess ? 0 : 1, response.Message);
        }
        //编辑
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit(PostModel model)
        {
            if (!EmailConfirmed)
                return JsonResultForFly(1, "请先验证邮箱哦.");
            return AddOrEdit(model);
        }
        //发贴
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Add(PostModel model)
        {
            if (!EmailConfirmed)
                return JsonResultForFly(1, "请先验证邮箱哦.");
            return AddOrEdit(model);
        }
        //上传文件
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Upload(HttpPostedFileBase f)
        {
            if (!IsLogin)
                return JsonResultForFly(1, "请先登录.");
            try
            {
                var files = Request.Files;
                if (files.Count == 0)
                    return Json(new
                    {
                        status = 1,
                        msg = "请选择要修改的头像"
                    });
                if (!EmailConfirmed)
                    return JsonResultForFly(1, "请先验证邮箱哦.");

                var curFile = files[0];
                if ((curFile.ContentLength / 1024) > 150)
                {
                    return Json(new
                    {
                        status = 1,
                        msg = "请选择小于150KB的图片."
                    });
                }

                //获取保存路径
                var filesUrl = Server.MapPath("~/Uploads/PostImages/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/");
                if (Directory.Exists(filesUrl) == false)//路径不存在则创建
                    Directory.CreateDirectory(filesUrl);
                var fileName = Path.GetFileName(curFile.FileName);
                //文件后缀名
                var filePostfixName = fileName.Substring(fileName.LastIndexOf('.'));
                //新文件名
                var newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + filePostfixName;
                var path = Path.Combine(filesUrl, newFileName);
                //保存文件
                curFile.SaveAs(path);

                var newPath = Domain + "Uploads/PostImages/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + newFileName;

                return Json(new
                {
                    status = 0,
                    msg = "上传成功",
                    url = newPath
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    status = 1,
                    msg = "上传失败、错误信息：" + ex.Message
                });
            }
        }

        private ActionResult AddOrEdit(PostModel model)
        {
            if (model == null)
                return JsonResultForFly(1, "请勿传递非法参数，请刷新重试！");

            if (model.Title.Length < 10)
                return JsonResultForFly(1, "标题不能少于10个字符！");
            if (model.Content.Length < 20)
                return JsonResultForFly(1, "内容不能少于20个字符！");

            //验证验证码是否正确
            var sessionVerifyCode = Session["VerifyCode"];
            if (sessionVerifyCode == null || model.Vercode != sessionVerifyCode.ToString())
                return JsonResultForFly(1, "验证码输入错误！");

            var service = new PostService();
            //编辑
            if (model.Id != 0)
            {
                var entity = service.GetPostById(model.Id);
                if (entity == null)
                    return JsonResultForFly(1, "请勿传递非法参数，请刷新重试！！");

                entity.Content = model.Content;
                entity.PostCategoryId = model.PostCateogryId;
                //entity.Reward = model.Reward;
                var response = service.UpdatePost(entity);
                return JsonResultForFly(response.IsSuccess ? 0 : 1, response.Message, "/post/" + entity.Id);
            }
            else
            {
                var entity = new Post
                {
                    Title = model.Title,
                    Content = model.Content,
                    UserId = CurrentUserId,
                    PostCategoryId = model.PostCateogryId,
                    Reward = model.Reward,
                    PostStatus = PostStatus.Open,
                    Sort = 0,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    Hits = 0,
                    Collection = 0,
                    IsShow = true
                };
                var response = service.SendPost(entity);
                return JsonResultForFly(response.IsSuccess ? 0 : 1, response.Message, "/post/" + entity.Id);
            }
        }

    }
}